'use strict';
const express = require('express');
const router = express.Router();
const qs = require('querystring');
const request = require('request');
const Fiber = require('fibers');
const config = require('../config');
const wxapi = require('../wxapi');
const db = require('../model/db');

router.get('/', function (req, res, next) {
    res.send('respond with agent');
});

// 三级代理入口
router.get('/login', function (req, res) {
    if (!req.session || !req.session.authenticated) {
        // 没有登录
        // 获取微信用户信息后跳转到代理主页面
        let queryParams = {
            appid: config.appId,
            redirect_uri: 'http://www.silinan.com/agent/home/',
            response_type: 'code',
            scope: 'snsapi_userinfo',
            secret: config.appSecret,
        };

        let oauthUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
            qs.stringify(queryParams) + '#wechat_redirect';
        // 跳转到授权页面
        res.redirect(oauthUrl);
    } else {
        // 获取代理账号信息
        let ret = {
            err: 0,
            userid: 0,
            nickname: req.session.nickname,
            tx_cash: 0,
            today_cash: 0,
        };
        let sql = "CALL mjjy_agent.cp_agent_auth(?,?,?)";
        db.pool.getConnection(function (err, connection) {
            let db_ret = 0;
            if (err) {
                res.send(ret);
                return;
            }
            connection.query(sql, req.session.unionid, req.session.nickname, db_ret,
                (error, results, fields) => {
                    connection.release();
                    ret.err = error;
                    if (error) {
                        ret.err = -1;
                        console.log('error running query', error);
                    } else {
                        ret.err = db_ret;
                        if (db_ret == 1) {
                            req.userid = results[0].userid;
                            ret.tx_cash = results[0].cash;
                            ret.today_cash = results[0].today_cash;
                        }
                    }
                    res.end(ret);
                });
        });
    }
});

// 账号密码登录(调试用)
router.post('/login_debug', function (req, res) {
    let userid = req.body.userid;
    let password = req.body.password;
    if (!userid || !password) {
        res.end();
        return;
    }
    db.agentLoginZH(userid, password, (resp) => {
        if (resp.ret == 1) {
            req.session.authenticated = true;
            req.session.userid = userid;
        }
        res.send(JSON.stringify(resp));
    });
});

// 微信回调
router.get('/home', function (req, res) {
    if (req.query.code == null) {
        console.log('request agent home page but code is null!');
        return;
    }
    let code = req.query.code;
    wxapi.getOAuthAccessToken(code, function (err, result) {
        if (err) {
            console.log('get oauth access_token failed!');
            return;
        }
        console.log(result);
        let access_token = result.access_token;
        let openid = result.openid;
        if (access_token == null || openid == null) {
            console.log('get oauth access_token or openid failed!');
            return;
        }
        // 获取用户个人信息
        let param = {
            access_token: json.access_token,
            openid: json.openid
        }
        let url = 'https://api.weixin.qq.com/sns/userinfo?'
            + querystring.stringify(param);
        https_get(url, (data) => {
            if (data == null) {
                console.log('get weixin userinfo failed!');
                return;
            }
            try {
                let json = JSON.parse(data);
                if (json.openid == null) {
                    console.log('get weixin user info error:' + json);
                    return;
                }
                //
                // 成功获取到微信用户信息
                // 使用全局唯一unionid
                //
                console.log('wx openid:' + json.unionid);
                // 登录成功
                req.session.authenticated = true;
                req.session.unionid = unionid;
                req.session.nickname = json.nickname;
                // 设置cookie
                // 跳转到代理主页面
                res.sendfile('agent3/index.html');
            } catch (e) {
                console.log(e.message);
            }
        });
    });
});

// 查询下级
// type: 0 下级玩家
// type: 1 下级代理
router.get('/sub', function (req, res) {
    let userid = req.query.userid;
    let type = req.query.type;
    console.log("agent:userid="+userid+",type="+type);
    if (!userid || !type) {
        res.end();
        return;
    }
    db.agentSub(userid, type, (resp) => {
        res.send(JSON.stringify(resp));
    });
});

// 查询提现订单
router.get('/cash', function (req, res) {
    let userid = req.query.userid;
    if (!userid) {
        res.end();
        return;
    }
    db.agentOrder(userid, (resp) => {
        res.send(JSON.stringify(resp));
    });
});

// 查询收益明细
router.get('/profit', function (req, res) {
    let userid = req.query.userid;
    let date = req.query.date;
    let leixin = req.query.leixin;
    if (!userid || !date || !leixin) {
        res.end();
        return;
    }
    db.profitDetail(userid, date, leixin, (resp) => {
        res.send(JSON.stringify(resp));
    });
});

// 提现
router.get('/present', function (req, res) {
    let userid = req.query.userid;
    let tx_cash = req.query.tx_cash;
    console.log("[agent] /present,userid="+userid+",tx="+tx_cash);
    if (!userid || !tx_cash) {
        res.end();
        return;
    }
    console.log("[agent] /present,userid="+userid+",tx="+tx_cash);
    db.doTx_cash(userid, tx_cash, (resp) => {
        res.send(JSON.stringify(resp));
    });
});

router.get('/myinfo', function (req, res) {
    res.send('hello myinfo');
});

module.exports = router;
